<template>
  <Head title="结算" />
  <ShopLayout>
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <h1 class="text-3xl font-light text-gray-900 mb-8">结算</h1>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- 左侧：收货地址和支付方式 -->
          <div class="lg:col-span-2 space-y-6">
            <!-- 收货地址 -->
            <div class="bg-white rounded-2xl p-8 shadow-sm">
              <AddressSelector
                :addresses="addresses"
                :provinces="provinces"
                v-model:selected-address-id="form.address_id"
                @address-selected="handleAddressSelected"
              />
            </div>


            <!-- 优惠券选择 -->
            <div class="bg-white rounded-2xl p-8 shadow-sm">
              <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-light text-gray-900">优惠券</h2>
                <button 
                  @click="showCouponModal = true"
                  class="text-gray-500 hover:text-gray-900 text-sm font-medium transition-colors duration-200"
                >
                  查看全部 ({{ availableCoupons.length }})
                </button>
              </div>
              <CouponSelector
                :available-coupons="availableCoupons"
                :unavailable-coupons="unavailableCoupons"
                :selected-coupon="selectedCoupon"
                :show-modal="showCouponModal"
                @select="handleCouponSelect"
                @remove="handleCouponRemove"
                @close-modal="showCouponModal = false"
              />
            </div>

            <!-- 订单备注 -->
            <div class="bg-white rounded-2xl p-8 shadow-sm">
              <h2 class="text-2xl font-light text-gray-900 mb-6">订单备注</h2>
              <textarea
                v-model="form.notes"
                rows="3"
                class="w-full px-4 py-3 border border-gray-300 rounded-2xl focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent resize-none"
                placeholder="如有特殊需求，请在此留言..."
              ></textarea>
            </div>
          </div>

          <!-- 右侧：订单摘要 -->
          <div class="lg:col-span-1">
            <div class="bg-white rounded-2xl p-6 shadow-sm sticky top-8">
              <h2 class="text-xl font-medium text-gray-900 mb-6">订单摘要</h2>

              <!-- 商品明细 -->
              <div class="space-y-3 pb-4 border-b border-gray-200 mb-4">
                <div v-for="item in items" :key="item.id || item.product_id" class="flex gap-4">
                  <img :src="item.image || '/images/placeholder.jpg'" :alt="item.name" class="w-16 h-16 object-cover rounded-lg" />
                  <div class="flex-1 min-w-0">
                    <p class="text-sm font-medium text-gray-900 truncate">{{ item.name }}</p>
                    <p v-if="item.specs && item.specs.length > 0" class="text-xs text-gray-500 mt-0.5">
                      {{ item.specs.map(s => s.value).join(' / ') }}
                    </p>
                    <div class="flex items-center justify-between mt-1">
                      <span class="text-sm text-gray-600">× {{ item.quantity }}</span>
                      <span class="text-sm font-medium text-gray-900">¥{{ (item.price * item.quantity).toLocaleString() }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 价格明细 -->
              <div class="space-y-3 mb-6">
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">商品小计</span>
                  <span class="text-gray-900">¥{{ (currentSummary.subtotal || 0).toLocaleString() }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">运费</span>
                  <span class="text-gray-900">
                    <span v-if="(currentSummary.shipping || 0) === 0">免运费</span>
                    <span v-else>¥{{ (currentSummary.shipping || 0).toLocaleString() }}</span>
                  </span>
                </div>
                <!-- 优惠券折扣 -->
                <div v-if="(currentSummary.coupon_discount || 0) > 0" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠券折扣</span>
                  <span class="text-red-600">-¥{{ (currentSummary.coupon_discount || 0).toLocaleString() }}</span>
                </div>
                <!-- 其他优惠 -->
                <div v-if="(currentSummary.discount || 0) > 0" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠</span>
                  <span class="text-red-600">-¥{{ (currentSummary.discount || 0).toLocaleString() }}</span>
                </div>
                <div class="pt-3 border-t border-gray-200">
                  <div class="flex justify-between items-center">
                    <span class="text-base font-medium text-gray-900">应付总额</span>
                    <span class="text-2xl font-medium text-gray-900">¥{{ (currentSummary.total || 0).toLocaleString() }}</span>
                  </div>
                </div>
              </div>

              <!-- 提交订单按钮 -->
              <button
                @click="submitOrder"
                :disabled="form.processing || !form.address_id"
                class="w-full bg-gray-900 text-white py-4 px-6 rounded-2xl font-medium hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <span v-if="form.processing">提交中...</span>
                <span v-else>提交订单</span>
              </button>

              <p class="text-xs text-gray-500 text-center mt-4">
                点击"提交订单"即表示您同意遵守我们的服务条款
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>


  </ShopLayout>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Head, router, useForm } from '@inertiajs/vue3'
import { Dialog, DialogPanel, DialogTitle, TransitionChild, TransitionRoot } from '@headlessui/vue'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'
import AddressSelector from '@/Components/Address/AddressSelector.vue'
import CouponSelector from '@/Components/CouponSelector.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  items: { type: Array, default: () => [] },
  summary: { type: Object, default: () => ({ subtotal: 0, shipping: 0, discount: 0, total: 0 }) },
  addresses: { type: Array, default: () => [] },
  provinces: { type: Array, default: () => [] },
  isBuyNow: { type: Boolean, default: false },
  availableCoupons: { type: Array, default: () => [] },
  unavailableCoupons: { type: Array, default: () => [] },
})

const { showSuccess, showError } = useNotification()

// 优惠券相关
const selectedCoupon = ref(null)
const couponDiscount = ref(0)
const showCouponModal = ref(false)

// 实时价格数据
const currentSummary = ref({
  subtotal: props.summary?.subtotal || 0,
  shipping: props.summary?.shipping || 0,
  discount: props.summary?.discount || 0,
  coupon_discount: 0,
  total: props.summary?.total || 0
})

// 计算价格
const calculatePrice = async (userCouponId = null) => {
  try {
    const response = await fetch(route('checkout.calculate-price'), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
      },
      body: JSON.stringify({
        user_coupon_id: userCouponId
      })
    })
    
    const result = await response.json()
    
    if (result.success && result.data) {
      currentSummary.value = {
        subtotal: result.data.subtotal || 0,
        shipping: result.data.shipping || 0,
        discount: result.data.discount || 0,
        coupon_discount: result.data.coupon_discount || 0,
        total: result.data.total || 0
      }
    } else {
      showError('价格计算失败', result.message || '请稍后重试')
    }
  } catch (error) {
    console.error('Price calculation error:', error)
    showError('价格计算失败', '网络错误，请稍后重试')
    // 保持当前值不变
  }
}

// 订单表单
const form = useForm({
  address_id: props.addresses.find(addr => addr.is_default)?.id || null,
  notes: '',
  user_coupon_id: null,
})

// 页面加载时初始化价格
onMounted(() => {
  // 确保价格数据正确初始化
  if (props.summary && props.summary.subtotal > 0) {
    currentSummary.value = {
      subtotal: props.summary.subtotal || 0,
      shipping: props.summary.shipping || 0,
      discount: props.summary.discount || 0,
      coupon_discount: 0,
      total: props.summary.total || 0
    }
  } else {
    // 如果 props.summary 不可用，使用默认值
    currentSummary.value = {
      subtotal: 0,
      shipping: 0,
      discount: 0,
      coupon_discount: 0,
      total: 0
    }
  }
})

// 地址弹窗
// 处理地址选择
const handleAddressSelected = (address) => {
  form.address_id = address.id
}

// 处理优惠券选择
const handleCouponSelect = async (coupon) => {
  selectedCoupon.value = coupon
  
  // 调用后端API计算价格
  const userCouponId = coupon.user_coupon_id || coupon.id
  await calculatePrice(userCouponId)
}

// 处理优惠券移除
const handleCouponRemove = async () => {
  selectedCoupon.value = null
  
  // 调用后端API重新计算价格（不使用优惠券）
  await calculatePrice(null)
}

// 提交订单
const submitOrder = () => {
  if (!form.address_id) {
    showError('请选择收货地址', '')
    return
  }

  // 添加优惠券信息到表单数据
  form.user_coupon_id = selectedCoupon.value?.user_coupon_id || null

  form.post(route('checkout.submit'), {
    onError: (errors) => {
      const errorMessage = Object.values(errors)[0]
      showError('订单提交失败', errorMessage || '请检查信息')
    }
  })
}
</script>
